#include "video/TextureManager.h"
#include "defines.h"
#include <assert.h>

namespace KEngine
{
	TextureManager::TextureManager():_device(0)
	{

	}

	TextureManager::~TextureManager()
	{
		ResMap::iterator it = _resMap.begin();
		for(;it!=_resMap.end();++it)
		{
			assert(it->second->getRefCount()==1);
			KSafeRelease(it->second);
		}
		_resMap.clear();
	}
	
	Texture* TextureManager::create(std::string& name)
	{
		Texture* p = getT(name);
		if(p)
		{
			p->addRef();
			return p;
		}

		p = new Texture();
		if(!p->loadFromFile(_device,name.c_str()))
		{
			KSafeRelease(p);
			return 0;
		}
		_resMap[name] = p;
		return p;
	}

	void TextureManager::releaseByName(std::string& name)
	{
		ResMap::iterator it = _resMap.find(name);
		if(it!=_resMap.end())
		{
			Texture* p = it->second;
			if(p->getRefCount()==1)
			{
				_resMap.erase(it);
			}
			KSafeRelease(p);
		}
		else
		{
			assert(0);
		}
	}

}